<?php
// +----------------------------------------------------------------------
// | RXThinkCMF敏捷开发框架 [ 赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | 版权所有 2018~2023 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | Licensed LGPL-3.0 RXThinkCMF并不是自由软件，未经许可禁止去掉相关版权
// +----------------------------------------------------------------------
// | 官方网站: https://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: @牧羊人 团队荣誉出品
// +----------------------------------------------------------------------
// | 版权和免责声明:
// | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
// | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
// | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
// | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
// | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
// | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
// | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
// | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
// | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\model\Clss;
use app\admin\model\Match;
use app\admin\model\Member;
use app\admin\model\Project;
use app\admin\model\SportRecord;
use app\admin\model\Standard;
use app\admin\model\Task;
use app\admin\service\LoginService;
use think\Db;
use think\facade\Cache;

/**
 * 系统登录-控制器
 * @author 牧羊人
 * @since 2020/11/19
 * Class Login
 * @package app\admin\controller
 */
class Login extends Backend
{
    public function index()
    {
        return $this->jsonReturn('');
    }

    public function test3()
    {
        $date = date('Y-m-d');
		$date = '2024-12-14';
        $this->tongbuSport($date.' 00:00:00',$date.' 23:00:00');
    }

    public function test2()
    {
        $date = date('Y-m-d');
        $this->tongbuSport($date.' 00:00:00',$date.' 23:00:00');
        cacl_bmi();
    }
    public function test()
    {
        $date = strtotime('2025-03-17');
        $end = time();
        //$end = strtotime('2025-03-17');
        do {
            $this->tongbuSport(date('Y-m-d 00:00:00', $date), date('Y-m-d 23:59:59', $date + 86399));
            $date += 86400;
            sleep(5);
        } while ($date < $end);
     //   cacl_bmi();
    }
    /**
     * 同步运动记录
     * @return mixed
     * @since 2020/11/20
     * @author 牧羊人
     */
    public function tongbuSport($start=null,$end=null)
    {
        // 最近一天开始
        $startTime = $start?strtotime($start)*1000:strtotime('-1 day')*1000; // 将日期转换为毫秒时间戳
        //$startTime = strtotime('2023-11-09 00:00:00')*1000;
        // 当前时间
        $endTime = $end?strtotime($end)*1000:time()*1000; // 将日期和时间转换为毫秒时间戳
        //$endTime = strtotime('2023-11-09 23:59:59')*1000;
        $types = [1,2];//数据类型 1：校内体育测试 2：校内体育锻炼 3：校外体育云作业 4：校园云体锻
        $tbnum = 0;
        $insert = 0;
        $update = 0;

        foreach ($types as $v) {

            $datas = [
                "type"=>$v,
                "startTimestamp"=> $startTime,
                "endTimestamp"=> $endTime,
                "pageNo"=> 1,
                "pageSize"=> 1
            ];
            $result = $this->service->synchronousResult($datas);//获取第三方同步数据
            $total = isset($result['result']['total'])?intval($result['result']['total']):0;
            $batchSize = 500; // 每批次500条数据
            $batchCount = $total?ceil($total / $batchSize):0;
            $rows = [];
            for ($i = 1; $i <= $batchCount; $i++) {
                $data = [];
                $datas = [
                    "type"=>$v,
                    "startTimestamp"=> $startTime,
                    "endTimestamp"=> $endTime,
                    "pageNo"=> $i,
                    "pageSize"=> $batchSize
                ];
                $result = $this->service->synchronousResult($datas);//获取第三方同步数据
                $rows = isset($result['result']['rows'])?$result['result']['rows']:[];
                $clss = new Clss();
                $member = new Member();
                $project = new Project();
                $task = new Task();
                $match = new Match();
                $standard = new Standard();
                $sdelarr = Db::name('sportrecord_del')->column('tbid');
                foreach ($rows as &$vs) {
                    if (is_array($sdelarr)&&!in_array($vs['id'],$sdelarr)) {
                        // code...

                        $mlist = $member->where('roll',$vs['testerNumber'])->cache(300)->find();
                        if ($mlist) { //判断匹配学籍号
                            $vs['type'] = $v;
                            $vs['tbid'] = $vs['id'];
                            $vs['memberId'] = $mlist['id'];
                            $vs['schoolId'] = $mlist['organization'];
                            $vs['gradeId'] = $mlist['grade'];
                            $vs['classId'] = $mlist['class'];
                            $vs['departmentsId'] = $mlist['superior'];
                            $vs['tiyu_superior'] = $mlist['tiyu_superior'];
                            $vs['professionalId'] = $mlist['professional'];
                            $vs['tiyu_professional'] = $mlist['tiyu_professional'];
                            $vs['tiyu_class'] = $mlist['features']?intval(json_decode($mlist['features'],true)[0]):0;
                            $vs['tiyu_class_string'] = $mlist['features'];
                            $vs['projectId'] = $project->where(['organization'=>$vs['schoolId'],'code'=>$vs['itemCode'],'mark'=>1])->cache(105)->value('id');
                            if ($vs['itemCode']=='weight'||$vs['itemCode']=='height') {
                                $vs['projectId'] = $project->where(['organization'=>$vs['schoolId'],'code'=>'BMI','mark'=>1])->cache(115)->value('id');
                            }
                            $stanArr = [];
                            if ($v==1) {//体测数据
                                $sta = $task->where('task_start','<=',$vs['startTime'])->where('task_end','>=',$vs['endTime'])->where('project',$vs['projectId'])->where('status',1)->where('mark',1)->find();

                                if ($sta) {
                                    if ($sta['class']) {
                                        $vs['tiyu_class'] = 0;
                                        $clssarr = json_decode($sta['class'],true);
                                        foreach ($clssarr as $val) {
                                            $str = '"'.$vs['memberId'].'"';
                                            $df = $clss->where('id',intval($val))->where('features','like','%'
                                                .$str.'%')->cache(125)->value('id');
                                            if ($df) {
                                                $vs['tiyu_class'] = intval($val);
                                                $vs['taskId'] = $sta['id']; //任务id
                                            }else{
                                                $vs['tiyu_class'] = 0;
                                                $vs['taskId'] = 0;
                                            }
                                        }
                                    }
                                    $vs['model'] = $sta['model']; //任务模式
                                    $stanArr = json_decode($standard->where('id',$sta['standard'])->value('standard'),true);
                                }else{
                                    $mat = $match->where('begin_time','<=',strtotime($vs['startTime']))->where('end_time','>=',strtotime($vs['endTime']))->where('projectId',$vs['projectId'])->where('mark',1)->find();
                                    if ($mat['mtype']==1) {
                                        $vs['type'] = 3; //体育赛事
                                    }

                                    if ($mat['mtype']==2) {
                                        $vs['type'] = 4; //院系测试
                                    }

                                    if ($mat) {
                                        $stanArr = json_decode($standard->where('project',$mat['projectId'])->cache
                                        (135)->value('standard'),true);
                                        $vs['taskId'] = $mat['id']; //赛事id
                                    }else{
                                        $vs['taskId']=0;
                                        $vs['type'] = 2; //体锻数据
                                        $pid = $project->where(['code'=>$vs['itemCode'],'mark'=>1])->cache
                                        (145)->value('id');
                                        if ($pid) {
                                            $stanArr = json_decode($standard->where(['organization'=>$vs['schoolId'],'project'=>$pid,'mark'=>1])->cache(155)->value('standard'),true);
                                        }

                                    }
                                }
                            }
                            if ($v==2) {//体锻数据
                                $pid = $project->where(['code'=>$vs['itemCode'],'mark'=>1])->cache(165)->value('id');
                                if ($pid) {
                                    $stanArr = json_decode($standard->where(['organization'=>$vs['schoolId'],'project'=>$pid,'mark'=>1])->cache(175)->value('standard'),true);
                                }

                            }
                            if ($stanArr) {
                                foreach ($stanArr as $vv) {
                                    if ($vv['sex']==$mlist['gender']) {
                                        switch ($vv['conditions']) {//判断成绩评级
                                            case 'gt':
                                                if ($vs['score']>$vv['target'][0]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            case 'egt':
                                                if ($vs['score']>=$vv['target'][0]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            case 'lt':
                                                if ($vs['score']<$vv['target'][0]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            case 'elt':
                                                if ($vs['score']<=$vv['target'][0]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;
                                            case 'between':
                                                if ($vs['score']>=$vv['target'][0]&&$vs['score']<=$vv['target'][1]) {
                                                    $vs['rating'] = $vv['level'];
                                                    $vs['pingscore'] = $vv['score'];
                                                }
                                                break;

                                            default:
                                                $vs['rating'] = 0;
                                                break;
                                        }
                                    }
                                }
                            }
                            //归类统计
                            $vs['stype'] = $project->where(['organization'=>$vs['schoolId'],'code'=>$vs['itemCode']])
                                ->cache(140)->value('type');
                            $vs['gender'] = $vs['gender']=='M'?1:2;
                            if (isset($vs['videoUrlList'])) {
                                $vs['videoUrlList'] = json_encode($vs['videoUrlList']);
                            }
                            $data[] = $vs;
                        }
                    }else{
                        trace($vs['id'].'记录本删除'.$vs['testerName'].'-'.$vs['testerNumber']);
                    }
                }
                unset($vs);
                $sportrecord = new SportRecord();
                foreach ($data as $vv) {
                    $tbid = $vv['tbid'];
                    $id = $sportrecord->where('tbid',$tbid)->value('id');
                    if (!$id) {
                        trace($tbid.'end 手动同步-插入操作'.$vv['testerName'].'-'.$vv['testerNumber']);
                        $insert++;
                        $sportrecord->allowField(true)->insert($vv);
                    }else{
                        trace($tbid.'end 手动同步-更新操作'.$vv['testerName'].'-'.$vv['testerNumber']);
                        $up = $vv;
                        $update++;
                        $sportrecord->allowField(true)->update($up);
                    }
                    $tbnum++;
                }
                unset($vv);
            }

        }

        echo  $start . ' ~ ' . $end . " => 同步".$tbnum."条".'-新增'.$insert.'条'.'-更新'.$update.'条<br/>';
    }
    /**
     * 初始化
     * @author 牧羊人
     * @since 2020/11/19
     */
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->service = new LoginService();
    }

    public function bim2()
    {
        cacl_bmi2();
    }

    /**
     * 验证码
     * @return mixed
     * @since 2020/11/14
     * @author 牧羊人
     */
    public function captcha()
    {
        $result = $this->service->captcha();
        return $this->jsonReturn($result);
    }

    public function xieyi()
    {
        $row = Db::table('think_xieyi')->where('id',input('id'))->find();
        //返回结果
        $message = array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $row,
        );
        return $this->jsonReturn($message);
    }

    /**
     * 登录
     * @return mixed
     * @since 2020/11/14
     * @author 牧羊人
     */
    public function login()
    {
        $param = request()->param();
        $key = 'user-login:' . md5($param['username'] ?? ($param['roll'] ?? ($param['realname'] ?? '')) . request()->ip());
        if ($lockType = Cache::get($key . '-lock')) {
            return $this->jsonReturn(message('访问频繁，请' . ($lockType == 1 ? '稍后' : '明天') . '再试！', false));
        }
        if (Cache::has($key . '-times')) {
            Cache::inc($key . '-times');
        } else {
            Cache::set($key . '-times', 0, 60);
        }
        if ((Cache::get($key . '-times') ?: 0) >= 5) {
            $expire = strtotime('today') + 86400 - time();
            Cache::set($key . '-lock', 1, 300);
            if (Cache::has($key . '-lock-times')) {
                Cache::inc($key . '-lock-times');
            } else {
                Cache::set($key . '-lock-times', 0, $expire);
            }
            if (Cache::get($key . '-lock-times') >= 3) {
                Cache::set($key . '-lock', 2, $expire);
            }
            return $this->jsonReturn(message('访问频繁，请稍后再试！', false));
        }
        if(isset($param['type']) && $param['type'] == 1){
          /*  $row = \app\admin\model\User::where('mobile',$param['mobile'])->find();
            if($row){
            }
            \app\admin\model\Memb::where('mobile',$param['mobile'])->find();*/
            $result = $this->service->student_login2($param);
            //'password' => get_password("123456" . $userInfo['username']),

            //$result = $this->service->mobile_login();
        }elseif(isset($param['type']) && $param['type'] == 3){
            if(empty($param['roll']) || empty($param['realname'])){
                return $this->jsonReturn(message("姓名和学籍号", false));
            }
            $result = $this->service->student_login($param);
        }else{

            $result = $this->service->login();

        }

        return $this->jsonReturn($result);
    }

    /**
     * 阿里云发送短信
     * @return void
     */
    public function get_code()
    {
        $result = $this->service->get_code();
        return $this->jsonReturn($result);
    }

    /**
     * 退出系统
     * @return mixed
     * @since 2020/11/14
     * @author 牧羊人
     */
    public function logout()
    {
        $result = $this->service->logout();
        return $this->jsonReturn($result);
    }

}